<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Area;
use Illuminate\Support\Facades\Auth;
use App\Repositories\AreaRepository;
use App\Http\Requests\Common\Area\ShowRequest;
use App\Http\Requests\Common\Area\QueryResource;
use App\Http\Requests\Common\Area\AreaCreate;
use App\Http\Requests\Common\Area\AreaUpdate;
use App\Http\Requests\Common\Area\AreaDestroy;

class AreaController extends Controller
{
    protected $areaRepository;

    /**
     * ArticlesController constructor.
     * @param AreaRepository $areaRepository
     */
    public function __construct(
        AreaRepository $areaRepository
    )
    {
        $this->areaRepository = $areaRepository;
    }

    /**
     * 获取地区列表
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $areas = $this->areaRepository->getAreas();
        return success($areas);
    }

    /**
     * 获取地区详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, Area $area)
    {
        return success($area);
    }


    /**
     * 创建地区
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param AreaCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(AreaCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $areas = $this->areaRepository->create($attributes);
        return stored($areas);
    }

    /**
     * 更新地区资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param AreaUpdate $request
     * @param Area $area
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(AreaUpdate $request, Area $area)
    {
        $areaAttr = $request->only([
            'area_name',
            'sort',
        ]);
        $area->update($areaAttr);
        return updated($area);
    }

    /**
     * 删除 地区 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param AreaDestroy $request
     * @param Area $area
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(AreaDestroy $request, Area $area)
    {
        $force = $request->get('force');
        $force ? $area->delete() : $area->forceDelete();
        return deleted();
    }

}
